from dash import Dash, dash_table, dcc, html, callback, Input, Output, State
import dash
import dash_bootstrap_components as dbc
import psycopg2.extras
import pandas as pd
import plotly.express as px
from Units import QUnits

dash.register_page(__name__, path='/')

def getPiedata():
    unit = QUnits()
    setting = unit.XML2ObjFromFile('./setting.xml').setting
    try:
        conn = unit.dbConnect(setting.pgsql)
        cursor = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
        cursor.execute('SELECT stock_label, capitalized * number AS cost, market_value * number AS curr FROM trading.owner_stock_view WHERE stock_code IS NOT NULL')
        df = pd.DataFrame(cursor.fetchall())
    except Exception as e:
        logging.warning(str(e))
    finally:
        unit.dbDisconnect(conn)
    return df

def layout():
    fig1 = px.pie(getPiedata(), values='cost', names='stock_label', title='原始成本分布图')
    fig2 = px.pie(getPiedata(), values='curr', names='stock_label', title='限价资产分布图')
    fig2.update_traces(textposition='inside', textinfo='percent+label')
    return html.Div(
        children=html.Div(
            children=[html.Div(children=dcc.Graph(figure=fig1), className='col-md-3'),
                      html.Div(children=dcc.Graph(figure=fig2), className='col-md-3')],
            className='row'
        ),
        className='container-fluid'
    )

